package packaged;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import models.sys.AdminUser;
import models.sys.Token;
import packaged.storage.Keeper;
import play.Play;
import play.mvc.Http;
import play.mvc.Scope;
import utils.CookiesUtils;

import java.util.UUID;

public class SessionManager {
    public static final String USER_SESSION_FLAG = "USER_LOGIN_FLAG_";
    public static final String USER_BROWSER_FLAG = "USER_BROWSER_FLAG_BY_TOPWEB";

    /**
     * 检查会话是否到期
     * @param session
     * @return
     */
    public static boolean sessionIsExpire(Scope.Session session) {
        return !Keeper.has(USER_SESSION_FLAG + session.getId());
    }

    public static void sessionIncreaseExpire(Scope.Session session) {
        Keeper.exp(USER_SESSION_FLAG + session.getId());
    }

    public static void setSession(Http.Request request, Http.Response response, Scope.Session session, AdminUser user, boolean remember) {
        Keeper.set(USER_SESSION_FLAG + session.getId(), user.toJSON().toString());
        if (remember) {
            //使用标识符与Token来确认唯一的浏览器
            //从Cookie中获取Flag标识符,对浏览器进行确认
            String flag = CookiesUtils.getCookie(request, USER_BROWSER_FLAG);
            if (flag == null) {
                flag = UUID.randomUUID().toString();
                CookiesUtils.addCookie(response, USER_BROWSER_FLAG, flag, (365 * 24 * 60 * 60));
            }
            String remember_token = UUID.randomUUID().toString();
            JSONObject content = new JSONObject();
            content.put("userid", user.id);
            content.put("username", user.username);
            content.put("password", user.password);
            TokenManager.recordToken(remember_token, flag, content.toString(), Play.configuration.getProperty("remember.overtime"), Token.Type.LOGIN_REMEMBER);
        }
    }

    public static void setAttribute(Scope.Session session, String key, String value) {
        session.put(key, value);
    }

    public static void removeSession(Scope.Session session) {
        Keeper.del(USER_SESSION_FLAG + session.getId());
    }

    public static String getAttribute(Scope.Session session, String key) {
        return session.get(key);
    }

    public static JSONObject getUserInfo(Scope.Session session) {
        if (!sessionIsExpire(session))
            return JSON.parseObject(Keeper.get(USER_SESSION_FLAG + session.getId()));
        return null;
    }
}
